//
//  MagaCoreApp.swift
//  MagaCore
//
//  Created by MrMessy on 2023/4/28.
//

import SwiftUI
import SwiftyStoreKit
import AppLovinSDK
import IQKeyboardManagerSwift
import FirebaseCore
import FirebaseMessaging
import AVKit
import ProgressHUD

class AppDelegate: NSObject, UIApplicationDelegate {

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
      // 通知
    FirebaseApp.configure()

    // [START set_messaging_delegate]
    Messaging.messaging().delegate = self
    // [END set_messaging_delegate]

    UNUserNotificationCenter.current().delegate = self

    application.registerForRemoteNotifications()

      IQKeyboardManager.shared.enable = true
      IQKeyboardManager.shared.resignOnTouchOutside = true
      IQKeyboardManager.shared.toolbarConfiguration.previousNextDisplayMode = .alwaysShow
      // 内购
    SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
      for purchase in purchases {
        switch purchase.transaction.transactionState {
        case .purchased, .restored:
          if purchase.needsFinishTransaction {
            // Deliver content from server, then:
            SwiftyStoreKit.finishTransaction(purchase.transaction)
          }
          // Unlock content
        case .failed, .purchasing, .deferred:
          break // do nothing
        @unknown default:
          print("")
        }
      }
    }
      // 测试
    let var_sdkKey = "uvhJ4TbOeXFQhPZZ_QABt6BDVAKP2q6cbKeICM2dn8FUM2ckUJ-5JD5I_qbBfIZ8C3ozNP29EJGKBfk8kxbJES"
    let initConfig = ALSdkInitializationConfiguration(sdkKey: var_sdkKey) { builder in
      builder.mediationProvider = ALMediationProviderMAX
    }
    // Initialize the SDK with the configuration
    ALSdk.shared().initialize(with: initConfig) { sdkConfig in
      // Start loading ads
    }

    return true
  }

  func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
    print("log-DidReceiveMemoryWarning")
  }

  // 设置屏幕支持的方向
  func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return var_screenRotator
  }

  func application(_ application: UIApplication,
                   didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    //    print(userInfo)
  }

  // [START receive_message]
  func application(_ application: UIApplication,
                   didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async
  -> UIBackgroundFetchResult {
    //    print(userInfo)

    return UIBackgroundFetchResult.newData
  }

  // [END receive_message]

  func application(_ application: UIApplication,
                   didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Unable to register for remote notifications: \(error.localizedDescription)")
  }

  func application(_ application: UIApplication,
                   didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")
    UserDefaults().set(String(data: deviceToken, encoding: .utf8), forKey: HTConfig.STATIC_userDefaults_deviceToken)
    Messaging.messaging().apnsToken = deviceToken
  }
}

// [START ios_10_message_handling]

extension AppDelegate: UNUserNotificationCenterDelegate {
  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification) async
  -> UNNotificationPresentationOptions {
    // Change this to your preferred presentation option
    return [[.alert, .sound]]
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse) async {
    let userInfo = response.notification.request.content.userInfo
    var var_params: [String: Any] = [:]
    var_params["jobid"] = userInfo["jobid"]
    var_params["type"] = userInfo["type"]
    var_params["text"] = userInfo["text"]

    let flag = userInfo["flag"] as! String
    var_params["flag"] = flag
    if (flag == "19" || flag == "20") {
      var_params["TTid"] = userInfo["TTid"]
      var_params["eps_id"] = userInfo["eps_id"]
    } else if (flag == "17") {
      var_params["mid"] = userInfo["mid"]
    }

    HTNetworkManager().ht_requestForBuried(.htEnumPushCl(var_flag: var_params["flag"] as! String, var_jobid: var_params["jobid"] as! String, var_text: var_params["text"] as! String, var_tab: "0"))

    // Print full message.
    HTAppStore.shared.dispatch(HTEnumPushAction.ht_pageToPlayScreen(var_push: var_params))
  }
}

// [END ios_10_message_handling]

extension AppDelegate: MessagingDelegate {
  // [START refresh_token]
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
    print("Firebase registration token: \(String(describing: fcmToken))")
    UserDefaults().set(fcmToken, forKey: HTConfig.STATIC_userDefaults_fcmToken)

    let dataDict: [String: String] = ["token": fcmToken ?? ""]
    NotificationCenter.default.post(
      name: Notification.Name("FCMToken"),
      object: nil,
      userInfo: dataDict
    )
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
  }

  // [END refresh_token]
}


@main
struct MagaCoreApp: App {

  @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
  @State var var_isVest: Bool = true

  init() {
    UITabBar.appearance().backgroundColor = UIColor(.white)
    UITabBar.appearance().unselectedItemTintColor = UIColor(Color(hex: "#393939"))

    let navibarAppearance = UINavigationBarAppearance()
    navibarAppearance.configureWithOpaqueBackground()
    navibarAppearance.backgroundColor = .white
    UINavigationBar.appearance().standardAppearance = navibarAppearance
    UINavigationBar.appearance().scrollEdgeAppearance = navibarAppearance

    let var_isVest = UserDefaults().string(forKey: HTConfig.STATIC_userDefaults_isVest)
    if (var_isVest == "false") {
      _var_isVest = State(initialValue: false)
    }

    let var_firstinstallTime = UserDefaults().string(forKey: HTConfig.STATIC_userDefaults_firstInstall)
    if (var_firstinstallTime == nil) {
      UserDefaults().set("\(Int(Date().timeIntervalSince1970))", forKey: HTConfig.STATIC_userDefaults_firstInstall)
    }

    // 配置音频会话
    do {
      try AVAudioSession.sharedInstance().setCategory(.playback)
    } catch {
      print("Failed to set audio session category: \(error)")
    }

    ProgressHUD.colorHUD = .lightGray
    ProgressHUD.colorBackground = UIColor(red: 255, green: 255, blue: 255, alpha: 0.2)
  }

  var body: some Scene {
    WindowGroup {
      if (var_isVest) {
        HTVestContentView { var_text in
          if (var_text == "OPEN") {
            var_isVest = false
            UserDefaults().set("false", forKey: HTConfig.STATIC_userDefaults_isVest)
          }
        }
      } else {
        HTContentView()
          .environmentObject(HTAppStore.shared)
      }
    }
  }
}
